<template>
  <div class="login-container">
    <div class="login-form">

      <p class="titleInfo">请把正脸对准摄像头</p>
      <div class="regInfo">
        <!-- <div class="tip">没有检测到脸</div> -->
        <div class="canvas">
          <!--video用于显示媒体设备的视频流，自动播放-->
          <video ref="vd" id="video" autoplay playsinline style="width: 200px;height: 200px"></video>
          <!--描绘video截图-->
          <canvas ref="cav" id="canvas" width="200" height="200"></canvas>
        </div>
      </div>
      <form id="myForm" method="post" ref="myForm" enctype="multipart/form-data">
      </form>

    </div>
    <div v-show="zzyz" class="tipShow">
      <el-alert
        title="正在验证,请稍等!"
        type="warning"
        center
        :closable="false"
        show-icon>
      </el-alert>
    </div>
    <div v-show="tipShow" class="tipShow">
      <el-alert
        title="验证成功"
        type="success"
        center
        :closable="false"
        show-icon>
      </el-alert>
    </div>
    <div v-show="errorShow" class="tipShow">
      <el-alert
        title="验证失败"
        type="error"
        center
        :closable="false"
        show-icon>
      </el-alert>
    </div>
    <div v-show="isFaceChecks" class="tipShow">
      <el-alert
        title="没有检测到真实人脸"
        type="error"
        center
        :closable="false"
        show-icon>
      </el-alert>
    </div>
  </div>

</template>

<script>


export default {
  components: {},
  name: 'faceLoginPage',
  data() {
    return {
      imgUrl: '',
      formData: {},
      states: false, // 摄像头是否打开 true 打开     false关闭
      zzyz: true, //正在验证
      tipShow: false, //成功
      errorShow: false, //失败
      isFaceChecks:false, //无法识别
      code: this.$route.query.code
    }
  },
  methods: {

    // 每三秒执行一次
    handleClick() {
      if (this.states) {
        // 注册拍照按钮的单击事件
        let video = this.$refs['vd']
        let canvas = this.$refs['cav']
        // 绘制成2d
        let context = canvas.getContext('2d')
        // 绘制画面
        context.drawImage(video, 0, 0, 200, 200)
        let base64Data = canvas.toDataURL('image/jpg')

        // 封装blob对象
        let blob = this.dataURItoBlob(base64Data, 'camera.jpg') // base64 转图片file
        let formData = new FormData()
        formData.append('file', blob)
        this.imgUrl = base64Data

        const data9 ={
          'file':formData,
          'code':this.code
        }

        this.$store.dispatch('user/checkFace',formData).then( res =>{
          if (res.code == 2000) {
            this.$store.dispatch('user/faceLogin', data9).then( res2 =>{
              if(res2.code == 2000) { // 验证成功
                this.zzyz = false
                this.tipShow = true
                setTimeout(() => {
                  window.location.href="about:blank";
                  window.close();
                },1000)
              }else{    // 验证失败
                this.zzyz = false
                this.errorShow = true
              }
            }).catch(function(error) {
                console.log(error)
            })
          } else {
            this.zzyz = false
            this.isFaceChecks = true
            return false
          }
        })
      }
    },

    // base转图片
    dataURItoBlob(base64Data) {
      var byteString
      if (base64Data.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(base64Data.split(',')[1])
      else byteString = unescape(base64Data.split(',')[1])
      var mimeString = base64Data
        .split(',')[0]
        .split(':')[1]
        .split(';')[0]
      var ia = new Uint8Array(byteString.length)
      for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i)
      }
      return new Blob([ia], { type: mimeString })
    }
  },


  created() {
    this.$nextTick(() => {
      let _this = this
      // 访问用户媒体设备的兼容方法
      const getUserMedia = (constrains, success, error) => {
        let video = _this.$refs['vd'];
        if (navigator.mediaDevices.getUserMedia) {
          // 最新标准API
          let myCons = {...constrains,video:true}
          navigator.mediaDevices
            .getUserMedia(constrains)
            .then((stream)=>{
              video.srcObject =stream
              video.play();
              _this.states = true
            })
            .catch(error)
        } else if (navigator.webkitGetUserMedia) {
          // webkit内核浏览器
          navigator
            .webkitGetUserMedia(constrains)
            .then(success)
            .catch(error)
        } else if (navigator.mozGetUserMedia) {
          // Firefox浏览器
          navigator
            .mozGetUserMedia(constrains)
            .then(success)
            .catch(error)
        } else if (navigator.getUserMedia) {
          // 旧版API
          navigator
            .getUserMedia(constrains)
            .then(success)
            .catch(error)
        }
      }
      let video = this.$refs['vd']
      let canvas = this.$refs['cav']
      // debugger
      let context = canvas.getContext('2d')

      // 成功的回调函数
      function success(stream) {
        _this.states = true
        // 兼容webkit内核浏览器
        let CompatibleURL = window.URL || window.webkitURL
        // 将视频流设置为video元素的源
        video.src = CompatibleURL.createObjectURL(stream)
        // 播放视频
        video.play()
      }

      // 异常的回调函数
      function error(error) {
        console.log('访问用户媒体设备失败：', error.name, error.message)
      }

      if ( navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia ) {
        // 调用用户媒体设备，访问摄像头
        getUserMedia(
          { video: {width:200,height:200} },
          success,
          error
        )
      } else {
        alert('你的浏览器不支持访问用户媒体设备')
      }
    })
  },

  mounted: function() {
    setInterval(this.handleClick, 2000)
  },

  // 组件更新
  // updated: function() {}

}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .el-alert__title,.el-alert__icon{font-size: 20px;}
  .regInfo {
    width: 200px;
    height: 200px;
    overflow: hidden;
    border: 1px solid #ccc;
    border-radius: 50%;
    margin: 0 auto;
    position: relative;
    .tip {
      position: absolute;
      top: 0;
      width: 100%;
      height: 40px;
      line-height: 40px;
      background: rgba(0, 0, 0, 0.2);
      text-align: center;
    }
    .canvas {
      position: absolute;
      top: 0;
      width: 100%;
    }
  }
  .titleInfo {
    text-align: center;
    font-weight: 700;
    padding: 30px 0 20px;
  }
  .tipShow{position: absolute;top:50%;left: 50%;width:180px;margin-left:-90px;}
</style>
